import Mn from 'backbone.marionette';
import ExpenseKmCollectionView from './ExpenseKmCollectionView.js';
import Radio from 'backbone.radio';
import {
    formatAmount,
    round
} from 'math.js';


const ExpenseKmTableView = Mn.View.extend({
    template: require('./templates/ExpenseKmTableView.mustache'),
    regions: {
        lines: {
            el: 'tbody',
            replaceElement: true
        }
    },
    ui: {
        add_btn: 'button.add',
    },
    events: {
        'click @ui.add_btn': 'onAdd',
    },
    childViewTriggers: {
        'kmline:edit': 'kmline:edit',
        'kmline:delete': 'kmline:delete',
        'kmline:duplicate': 'kmline:duplicate',
    },
    collectionEvents: {
        'change:category': 'render',
    },
    initialize() {
        var channel = Radio.channel('facade');
        this.totalmodel = channel.request('get:totalmodel');
        this.categoryId = this.getOption('category').value;
        this.listenTo(
            channel,
            'change:kmlines_' + this.categoryId,
            this.render.bind(this)
        );
    },
    isCollectionEmpty() {
        return this.collection.find(
            x => x.get('category') == this.categoryId
        ) === undefined;
    },
    templateContext() {
        var is_achat = false;
        let is_empty = this.isCollectionEmpty();

        if (this.getOption('category').value == 2) is_achat = true;
        return {
            total_km: round(this.totalmodel.get('km_' + this.categoryId), 2) + "&nbsp;km",
            total_ttc: formatAmount(this.totalmodel.get('km_ttc_' + this.categoryId)),
            category: this.getOption('category'),
            edit: this.getOption('edit'),
            is_achat: is_achat,
            is_empty: is_empty,
            is_not_empty: !is_empty,
        };
    },
    onAdd() {
        this.triggerMethod(
            'kmline:add',
            this, {
                category: this.getOption('category').value
            },
        );
    },
    onRender() {
        var view = new ExpenseKmCollectionView({
            collection: this.collection,
            category: this.getOption('category'),
            edit: this.getOption('edit'),
        });
        this.showChildView('lines', view);
    },
});
export default ExpenseKmTableView;